package player

import (
	"github.com/gin-gonic/gin"
	"go_server/game_server/api/service/bag"
	"go_server/game_server/protocol/pb"
	"go_server/zinx/zlog"
	"net/http"
	"strconv"
)

type itemsRquest struct{
	RoleId int64
	Items []int32
}

func GetBagItems(ctx *gin.Context) {
	roleId, err := strconv.Atoi(ctx.Query("roleId"))
	if err != nil {
		ctx.String(http.StatusBadRequest, "param err!!")
		return
	}

	itemMap, code := bag.GetRoleBagInfo(int64(roleId))
	if code != pb.ErrorCodeManager_SUCCESS {
		ctx.String(http.StatusBadRequest, "param err!!")
		return
	}
 	ctx.JSON(http.StatusOK, itemMap)
}

func RemoveBagItems(ctx *gin.Context) {
	var request itemsRquest
	if err := ctx.ShouldBindJSON(&request); err != nil {
		zlog.Errorf("RemoveBagItems bind request param failed: %s", err)
		ctx.String(http.StatusBadRequest, "获取参数失败！！！")
		return
	}

	size := len(request.Items)
	if size <= 0 {
		ctx.String(http.StatusOK, "删除玩家:%d 指定物品成功！！！", request.RoleId)
		return
	}

	if size % 2 != 0 {
		ctx.String(http.StatusBadRequest, "指定物品参数个数不正确,必须是2的整数倍，当前个数: %d", size)
		return
	}

	removeItems := make([][]int32, 0, size / 2)
	for i := 0; i < size; i += 2 {
		itemInfo := make([]int32, 2, 2)
		itemInfo[0] = request.Items[i]
		itemInfo[1] = request.Items[i + 1]
		removeItems = append(removeItems, itemInfo)
	}

	if _, ok := bag.SubItemArray(request.RoleId, removeItems); !ok {
		ctx.String(http.StatusBadRequest, "删除玩家: %d 指定物品失败！！！,请检查参数！", request.RoleId)
		return
	}
	ctx.String(http.StatusOK, "删除玩家:%d 指定物品成功！！！", request.RoleId)
}

func AddBagItems(ctx *gin.Context) {
	var request itemsRquest
	if err := ctx.ShouldBindJSON(&request); err != nil {
		zlog.Errorf("RemoveBagItems bind request param failed: %s", err)
		ctx.String(http.StatusBadRequest, "获取参数失败！！！")
		return
	}

	size := len(request.Items)
	if size <= 0 {
		ctx.String(http.StatusOK, "添加玩家:%d 指定物品成功！！！", request.RoleId)
		return
	}

	if size % 2 != 0 {
		ctx.String(http.StatusBadRequest, "指定物品参数个数不正确,必须是2的整数倍，当前个数: %d", size)
		return
	}

	addItems := make([][]int32, 0, size / 2)
	for i := 0; i < size; i += 2 {
		itemInfo := make([]int32, 2, 2)
		itemInfo[0] = request.Items[i]
		itemInfo[1] = request.Items[i + 1]
		addItems = append(addItems, itemInfo)
	}

	bag.AddItemArray(request.RoleId, addItems);
	ctx.String(http.StatusOK, "添加玩家:%d 指定物品成功！！！", request.RoleId)
}